#!/usr/bin/python

#
# Copyright 2008 Amit Shrestha
#

'''
This file is part of Words.

Words is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Words is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
'''

import sys

from java.awt.event import KeyListener
from java.awt.event import KeyEvent
from java.awt.event import ActionListener
from java.awt.event import MouseListener 
from java.awt.event import MouseEvent 
from javax.swing.event import HyperlinkListener
from javax.swing.event import HyperlinkEvent

from java.awt.event import WindowListener
from java.awt.event import WindowEvent

from javax.swing import JOptionPane
from javax.swing.text import Position

from core.dict import get_definitions
from gui.utility import display_html

class MyWindowListener(WindowListener):
    def __init__(self,main_class):
        self.main_class = main_class

    def windowActivated(self,e):
        pass
    
    def windowClosed(self,e):
        pass

    def windowClosing(self,e):
        print "Saving Changes..."
        if not self.main_class.save():
            JOptionPane.showMessageDialog(self.main_class.main_frame,"An error occured saving settings","Error",JOptionPane.INFORMATION_MESSAGE)
        sys.exit(0)
    
    def windowDeactivated(self,e):
        pass

    def windowIconified(self,e):
        pass

    def windowDeiconified(self,e):
        pass

    def windowOpened(self,e):
        self.main_class.main_frame.panel_output.output_box.grabFocus()

class KeyboardListener(KeyListener):
    def __init__(self,main_class):
        self.main_class = main_class

    def keyPressed(self,e):
        key_code = e.getKeyCode()
        key_char = e.getKeyChar()
        source = e.getSource()
        number_of_choices = self.main_class.number_of_choices
        if key_char in [str(x) for x in range(1,number_of_choices + 1)]:
            if self.main_class.correct_choice == int(key_char): 
                self.main_class.reveal_answer('Correct!')
            else:
                self.main_class.reveal_answer('Wrong!')
        elif (self.main_class.dframe and key_code == KeyEvent.VK_ENTER) and source.equals(self.main_class.dframe.txt_search):
            text = self.main_class.dframe.txt_search.getText().lower()
            word = self.main_class.db.get_word(text)
            if word:
                html = self.main_class.get_word_html(word)
                self.main_class.dframe.result_box.setText(html)
                self.main_class.dframe.result_box.setCaretPosition(0)
            else:
                print self.main_class.dframe.result_box.setText("Word not found")
        elif key_code == KeyEvent.VK_ENTER:
            self.main_class.test()
        elif key_code == KeyEvent.VK_ESCAPE and not (self.main_class.dframe and source.equals(self.main_class.dframe.txt_search)):
            self.main_class.reveal_answer('You could have guessed!')
        elif key_char == 'm':
            self.main_class.mark_mastered('Word has been marked mastered.')
        elif key_char == 'd' and not (self.main_class.dframe and source.equals(self.main_class.dframe.txt_search)):
            self.main_class.open_dictionary()
        elif (self.main_class.dframe and source.equals(self.main_class.dframe.txt_search)):
            text = self.main_class.dframe.txt_search.getText()
            index = self.main_class.dframe.list_box.getNextMatch(text,0,Position.Bias.Forward)
            if index != -1:
                self.main_class.dframe.list_box.setSelectedIndex(index)
                self.main_class.dframe.list_box.ensureIndexIsVisible(index)
        else:
            pass
    
    def keyReleased(self,e):
        pass
    
    def keyTyped(self,e):
        pass

class MyMouseListener(MouseListener):
    def __init__(self,main_class):
        self.main_class = main_class

    def mouseEntered(self,e):
        source = e.getSource()
        if source.equals(self.main_class.main_frame.menu_bar.file_menu_practice_sets):
            index_names = self.main_class.db.get_available_index_names()
            to_disable = []
            for x in index_names:
                indices = self.main_class.db.get_indices(x)
                if len(indices) <= 0:
                    to_disable.append(x)
            if len(to_disable) > 0:
                self.main_class.main_frame.menu_bar.disable_practice_sets(to_disable)
    
    def mouseClicked(self,e):
        source = e.getSource()
        if self.main_class.dframe:
            if source.equals(self.main_class.dframe.cmd_search):
                text = self.main_class.dframe.txt_search.getText().lower()
                self.main_class.dframe.list_box.setSelectedValue(text,True)
            elif e.getClickCount() >= 1:
                    text = self.main_class.dframe.list_box.getSelectedValue()
                    self.main_class.dframe.result_box.setText(text)
                    word = self.main_class.db.get_word(text)
                    if word:
                        html = self.main_class.get_word_html(word)
                        self.main_class.dframe.result_box.setText(html)
                        self.main_class.dframe.result_box.setCaretPosition(0)
                    else:
                        print self.main_class.dframe.result_box.setText("Word not found")


    def mouseExited(self,e):
        pass

    def mousePressed(self,e):
        pass

    def mouseReleased(self,e):
        pass

class MyHyperlinkListener(HyperlinkListener):
    def __init__(self,main_class):
        self.main_class = main_class

    def hyperlinkUpdate(self,e):
        if e.getEventType() == HyperlinkEvent.EventType.ACTIVATED:
            if e.getDescription() == "pronunciation_guide":
                html_file = open("files/pronunciation_guide.html",'r')
                html = html_file.read()
                html_file.close()
                display_html(html,"Pronunciation Guide",400,400)
            else:
                html = "<html><body><center><h1>Querying dict.org.<br>Please Wait...</h1></center></body></html>"
                html_frame = display_html(html, e.getDescription(), 400,400)
                html_frame.html_pane.addHyperlinkListener(self)

                html = "<html><body>"
                defns = get_definitions(e.getDescription()) 
                html += "<b>%d</b> definition(s) found" % len(defns)
                html += "<pre>"
                for x in defns: html += x + "<br/>"
                html += "</pre>"
                html += "</body></html>"
                html_frame.set_html(html)

class MenuListener(ActionListener):
    def __init__(self,main_class,index_names):
        self.main_class = main_class
        self.index_names = index_names

    def actionPerformed(self,e):
        source = e.getSource()
        if source.equals(self.main_class.main_frame.menu_bar.file_menu_exit):
            msg = "<html><body>"
            msg += "This is what the program does when you click the X button at the top right corner.<br>"
            msg += "It will save your changes and exit!<br><br> The program will now save your changes and exit. Click Ok to continue.</body></html>"
            confirm = JOptionPane.showConfirmDialog(self.main_class.main_frame,msg,"Plase Confirm",JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE)
            if confirm == JOptionPane.OK_OPTION:
                print "Saving Changes..."
                if not self.main_class.save():
                    JOptionPane.showMessageDialog(self.main_class.main_frame,"An error occured saving settings","Error",JOptionPane.INFORMATION_MESSAGE)
                sys.exit(0)
        elif source.equals(self.main_class.main_frame.menu_bar.file_menu_exit_without_save):
            confirm = JOptionPane.showConfirmDialog(self.main_class.main_frame,"All changes will be lost. Are you sure?","Please Confirm",JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE)
            if confirm == JOptionPane.OK_OPTION:
                sys.exit(0)
        elif source.equals(self.main_class.main_frame.menu_bar.file_menu_reset_number_of_times_tested):
            msg = "<html><body>"
            msg += "All words' <u>number of times tested</u> will be set to zero.<br/><br/>"
            msg += "This action requires exiting the program.<br/><br/>Are you sure?"
            confirm = JOptionPane.showConfirmDialog(self.main_class.main_frame,msg,"Please Confirm",JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE)
            if confirm == JOptionPane.OK_OPTION:
                self.main_class.db.reset_number_of_times_tested()
                if self.main_class.save():
                    JOptionPane.showMessageDialog(
                        self.main_class.main_frame,
                        "<html><body><u>Number of times tested</u> has been reset.<br/><br/>The program will now exit.</body></html>",
                        "Success",
                        JOptionPane.INFORMATION_MESSAGE
                    )
                    sys.exit(0)
                else:
                    JOptionPane.showMessageDialog(self.main_class.main_frame,"An error occured saving settings","Error",JOptionPane.INFORMATION_MESSAGE)
        elif source.equals(self.main_class.main_frame.menu_bar.file_menu_reset_mastered_words):
            msg = "<html><body>"
            msg += "All mastered words will be reset.<br/><br/>"
            msg += "This action requires exiting the program.<br/><br/>Are you sure?"
            confirm = JOptionPane.showConfirmDialog(self.main_class.main_frame,msg,"Please Confirm",JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE)
            if confirm == JOptionPane.OK_OPTION:
                self.main_class.db.reset_mastered_words()
                if self.main_class.save():
                    JOptionPane.showMessageDialog(
                        self.main_class.main_frame,
                        "<html><body>All mastered words have been reset.<br/><br/>The program will now exit.</body></html>",
                        "Success",
                        JOptionPane.INFORMATION_MESSAGE
                    )
                    sys.exit(0)
                else:
                    JOptionPane.showMessageDialog(self.main_class.main_frame,"An error occured saving settings","Error",JOptionPane.INFORMATION_MESSAGE)
        elif source.equals(self.main_class.main_frame.menu_bar.tools_menu_view_statistics):
            html = self.main_class.get_statistics_html()
            display_html(html,"Statistics",400,400)
        elif source.equals(self.main_class.main_frame.menu_bar.tools_menu_pronunciation_guide):
            html_file = open("files/pronunciation_guide.html",'r')
            html = html_file.read()
            html_file.close()
            display_html(html,"Pronunciation Guide",400,400)
        elif source.equals(self.main_class.main_frame.menu_bar.tools_menu_dictionary):
            self.main_class.open_dictionary()
        elif source.equals(self.main_class.main_frame.menu_bar.help_menu_help):
            html_file = open("files/help.html",'r')
            html = html_file.read()
            html_file.close()
            display_html(html,"Help",400,400)
        elif source.equals(self.main_class.main_frame.menu_bar.help_menu_about):
            html_file = open("files/about.html",'r')
            html = html_file.read()
            html_file.close()
            display_html(html,"About",400,400)
        elif source.getText() in self.index_names:
            self.main_class.set_active_index_name(source.getText())
